package com.t365.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.t365.pojo.SysMenu;
import com.t365.pojo.SysRole;
import com.t365.pojo.SysUser;
import com.t365.service.SysMenuService;
import com.t365.service.SysRoleService;
import com.t365.service.SysUserService;
import com.t365.utils.Constaints;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Jane
 * @date 2024-04-28 15:12
 */

@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    SysUserService userService;

    @Resource
    SysRoleService sysRoleService;

    @Resource
    SysMenuService sysMenuService;

    @RequestMapping("/doLogin")
    public String doLogin(String account
                    , String password
                    , Model model
                    , HttpSession session
                          ){
        System.out.println(">>>>>>>>>>>>>doLogin");
       /* if ("admin".equals(account)){
            if ("123456".equals(password)){
                System.out.println("ok");
                return "redirect:/user/toMain";
            }
        }*/
        String msg ="";
        SysUser userSession=userService.doLogin(account,password);
        if (null!=userSession){
            session.setAttribute("userSession",userSession);
            model.addAttribute(msg,"ok");
            return "redirect:/user/toMain";
        }
        model.addAttribute(msg,"账密错误,登录失败");
        return "login";//去login的请求
    }

    @RequestMapping("/toMain")
    public String toMain(HttpSession session){
        SysUser sysUser = (SysUser) session.getAttribute("userSession");
        List<SysMenu> menuList = sysMenuService.getMenuListByRidAndParentId(sysUser.getRoleid().intValue(), "0");
        session.setAttribute("menuList",menuList);
        return "frame.jsp";
    }


    @RequestMapping("/list")
    public String toUserList(Model model
                            , @RequestParam(required = false) String queryRealName
                            , @RequestParam(required = false) String queryRoleId
                            , @RequestParam(name = "pageIndex",required = false,defaultValue = "1") Integer pageIndex
                            ){
        model.addAttribute("roleList",sysRoleService.list());//查所有角色列表

        //获取用户所有信息
        Page<SysUser> page =new Page<>(pageIndex, Constaints.PAGE_SIZE);
        //userService.page(page,null);
        userService.getAllByRealnameAndRoleid(queryRealName,queryRoleId,page);
        model.addAttribute("mypage",page);

        return "/sysUser/list.jsp";
    }

    @RequestMapping("/view/{id}")
    public String toView(@PathVariable Integer id,Model model){
        SysUser sysUser =userService.getById(id);//按id查找用户信息  有roleId
        String roleName = sysRoleService.getById(sysUser.getRoleid()).getRoleName();
        sysUser.setRoleName(roleName);
        model.addAttribute(sysUser);
        return "/sysUser/view.jsp";
    }

    @RequestMapping("/modifyUser/{id}")
    public String toUserUpdate(@PathVariable Integer id,Model model){
        SysUser sysUser =userService.getById(id);//按id查找用户信息  有roleId

        List<SysRole> roleList =sysRoleService.list();

        model.addAttribute(sysUser);
        model.addAttribute("roleList",roleList);

        return "/sysUser/update.jsp";
    }
    @RequestMapping("/update")
    public String toUserUpdate(SysUser sysUser
                            , @RequestParam(value = "attach",required = false) MultipartFile[] attachs
                               , HttpServletRequest request
                               ){  //请求里面的

        /*Integer id = Integer.valueOf(request.getParameter("id"));
        SysUser initUser = userService.getById(id);  //库里面的

        String realname =request.getParameter("realname");

        initUser.setRealname(realname);*/
        /*Date date =new Date();
        sysUser.setUpdatedtime(date);*/
        //session.setAttribute("userSession",userSession);

        try {
            for (int i =0;i<attachs.length;i++){

                MultipartFile attach =attachs[i];

                if (!attach.isEmpty()){
                    //文件上传
                    String fileName = attach.getOriginalFilename    ();//源文件名称   a.png
                    String suffix = FilenameUtils.getExtension(fileName);//   png

                    fileName=UUID.randomUUID().toString().replace("-","")+"."+suffix;//ASDGF-DZXFCG12-234DSFDG.png
                   /* HttpServletRequest request;
                    request.getServletContext().getRealPath();// ssm_724/statics*/
                    String path="D:\\temp\\upload\\"+fileName;//文件名

                    //上传文件的位置


                    //String _path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadfiles");

                   /* File file =new File(_path) ;//文件夹
                    if (!file.exists())  file.mkdirs();//创建文件夹
                     file =new File(_path + File.separator + fileName );
                         */
                    File file =new File(path);
                    if (!file.exists())  file.mkdirs();//创建文件夹

                    attach.transferTo(file);//传输

                    sysUser.setHeaderpic("statics/uploadfiles/"+fileName);

                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        userService.updateById(sysUser);

        return "redirect:/user/list";
    }
}
